package com.chap13;

import java.util.Arrays;
import java.util.concurrent.RecursiveAction;

/**
 * <p>
 * <code>MergeSortTask</code>
 * </p>
 *
 * @author junbao3
 * TODO
 * @date 2023-04-12 9:20
 * Copyright (C) 2021 IFlyTek. All rights reserved.
 */
public class MergeSortTask extends RecursiveAction {
    private int[] orignArray;
    private int threshold;

    public int[] getOrignArray() {
        return orignArray;
    }

    public void setOrignArray(int[] orignArray) {
        this.orignArray = orignArray;
    }

    public MergeSortTask(int[] orignArray, int threshold) {
        this.orignArray = orignArray;
        this.threshold = threshold;
    }

    @Override
    protected void compute() {
        if (orignArray.length<=threshold){
            Arrays.sort(orignArray);
            return ;
        }
        int middle = orignArray.length/2;
        int[] left = Arrays.copyOfRange(orignArray, 0, middle);
        int[] right = Arrays.copyOfRange(orignArray, middle, orignArray.length);

        MergeSortTask leftTask = new MergeSortTask(left, threshold);
        MergeSortTask rightTask = new MergeSortTask(right, threshold);

        //一开始的写法
//        invokeAll(leftTask,rightTask);


        //更容易理解的写法，但是有问题，可能有些线程没有充分利用
        // 提交任务
        leftTask.fork();
        rightTask.fork();
//
//        //合并结果
//        leftTask.join();
//        rightTask.join();
        orignArray = MergeSort.merge(leftTask.orignArray,rightTask.orignArray);

    }
}
